import 'dart:convert';
import 'dart:math';

import 'package:dotted_line/dotted_line.dart';
import 'package:flutter_menu/biz/order/detail/detail_controller.dart';
import 'package:flutter_menu/biz/order/detail/option/options_controller.dart';
import 'package:flutter_menu/biz/order/detail/package/group_fix.dart';
import 'package:flutter_menu/biz/order/widget/option_item.dart';
import 'package:flutter_menu/biz/order/widget/count_number_button.dart';
import 'package:flutter_menu/biz/order/detail/package/group_selectable.dart';
import 'package:flutter_menu/biz/order/widget/option_selector.dart';
import 'package:flutter_menu/biz/order/widget/spec_selector.dart';
import 'package:flutter_menu/model/product_model.dart';
import 'package:flutter_menu/res/app_design.dart';
import 'package:get/get.dart';

class OptionsDialog extends GetView<OptionsController> {
  const OptionsDialog({super.key});

  @override
  Widget build(BuildContext context) {
    var widthOptionDialog = 722.w;
    var heightOptionDialog = 975.h;
    return GetBuilder<OptionsController>(
        id: OptionsController.idSpecDialog,
        init: OptionsController(),
        builder: (controller) {
          debugPrint("OptionDialog Build");
          return Container(
            padding: EdgeInsets.symmetric(vertical: 30.w, horizontal: 26.w),
            width: widthOptionDialog,
            height: heightOptionDialog,
            child: Column(
              mainAxisSize: MainAxisSize.max,
              children: [
                Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text(DetailController.to.productName,
                        style: TextStyle(
                            fontSize: 35.sp,
                            color: AppColors.textInBottomSheet)),
                    SizedBox(height: 45.w),

                    // 数量选择器
                    const DottedLine(
                      dashColor: AppColors.text_BEBEBE,
                    ),
                    Row(
                      children: [
                        Text('dishOptionsQuality'.tr,
                            style: TextStyle(
                                fontSize: 26.sp,
                                color: AppColors.textInBottomSheet)),
                        const Spacer(),
                        Obx(() {
                          return CountNumberButton(
                            initialValue: max(controller.quantity.value, 1),
                            minValue: 1,
                            maxValue: 9999,
                            width: 158.w,
                            height: 46.w,
                            maxLength: 4,
                            numberEditable: false,
                            colorActive: AppColors.countNumberButtonActive,
                            colorInactive: AppColors.countNumberButtonInactive,
                            colorBg: AppColors.countNumberBg,
                            textStyle: TextStyle(
                                fontSize: 25.sp,
                                color: AppColors.textInBottomSheet,
                                fontWeight: AppStyle.semiBold),
                            onChanged: (value, isAdd) {
                              // Handle counter value changes
                              controller.setProductQuantity(value.toInt());
                            },
                          );
                        })
                      ],
                    ).paddingSymmetric(vertical: 8.w),
                    const DottedLine(
                      dashColor: AppColors.text_BEBEBE,
                    ),

                    // 规格列表
                    buildSpecWidget(),

                    SizedBox(
                      height: 28.w,
                    ),
                    // 备注输入框
                    buildTitleText('dishOptionsRemark'.tr),
                    SizedBox(
                      height: 15.w,
                    ),
                    TextField(
                      onChanged: (v) {},
                      style: TextStyle(
                          fontSize: AppDimen.sp_19,
                          color: AppColors.text_C59469,
                          height: 1.36),
                      controller: controller.remarkController,
                      maxLength: 164,
                      maxLines: 3,
                      decoration: InputDecoration(
                          hintStyle: const TextStyle(color: AppColors.text_666),
                          hintText: "dishOptionsRemarkPlaceholder".tr,
                          counterText: "",
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.r),
                              borderSide:
                                  const BorderSide(color: Color(0xFFD8B3A2))),
                          enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.r),
                              borderSide:
                                  const BorderSide(color: Color(0xFFD8B3A2))),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.r),
                              borderSide:
                                  const BorderSide(color: Color(0xFFD8B3A2))),
                          filled: true,
                          fillColor: Colors.white,
                          contentPadding: const EdgeInsets.only(
                              left: 11, top: 6, bottom: 8, right: 11)),
                    ),
                    SizedBox(height: 30.w),
                  ],
                ).scrollable().expanded(),
                SizedBox(height: 30.w),
                // 底部确认按钮
                buildConfirmButton(controller),
              ],
            ),
          ).commonDialog(onCloseTap: () {
            if (Get.isDialogOpen == true) {
              Get.back();
            }
          });
        });
  }

  Align buildConfirmButton(OptionsController controller) {
    return Align(
      alignment: Alignment.centerRight,
      child: ElevatedButton(
          onPressed: () {
            controller.confirmProductOption();
          },
          style: ElevatedButton.styleFrom(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(9.r)),
            ),
            backgroundColor: AppColors.bgTab,
            foregroundColor: AppColors.bgTab.withOpacity(0.5),
          ),
          child: Obx(() {
            var remaining = controller.remainingOfProduct.value;
            var buttonText = 'dishOptionsConfirm'.tr +
                'dishOptionsConfirmRemaining'.trArgs([remaining.toString()]);
            return Text(buttonText,
                style: TextStyle(
                    fontWeight: AppStyle.semiBold,
                    color: Colors.white,
                    fontSize: 22.sp));
          })).size(height: 69.w),
    );
  }

  Widget buildSpecWidget() {
    // 套餐
    var isPackage = DetailController.to.isPackage();
    return isPackage
        ? buildColumnForPackageGroup()
        : buildColumnForMultipleSpec();
  }

  // 套餐组件
  Widget buildColumnForPackageGroup() {
    return Obx(() {
      var groups = controller.groupWithFoods.value;
      return groups
          .map<Widget>((item) {
            var id = item.id ?? "";
            var isFix = item.isFix();
            var foods = item.foods;
            var foodsLength = foods.length;
            var max = min(item.max, foodsLength);
            debugPrint("buildColumnForPackageGroup: $foods");

            Widget child;
            if (isFix) {
              child = GroupFix(
                title: "${item.name}${"packageSelectHint".trArgs([
                      foodsLength.toString(),
                      foodsLength.toString()
                    ])}",
                options: foods,
                quantity: controller.quantity.value,
              );
            } else {
              child = GroupSelectable(
                  id: id,
                  title: "${item.name}${"packageSelectHint".trArgs([
                        foodsLength.toString(),
                        max.toString()
                      ])}",
                  max: max,
                  specList: foods);
            }

            return child.paddingOnly(top: 20.w);
          })
          .toList()
          .toColumn(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
          );
    });
  }

  // 规格组件
  Widget buildColumnForMultipleSpec() {
    var optionsBySelectedSpecId = controller.getOptionListBySelectedSpecId();
    var optionsByGroup = controller.getOptionListByGroup(optionsBySelectedSpecId);

    return Obx(() {
      return Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 规格
          SpecSelector(
            title: "dishOptionsSpec".tr,
            specList: controller.specWithOptions.value,
          ).paddingOnly(top: 20.w),
          // 选项 and 其他
          ...optionsByGroup.map((entry) {
            var key = entry.key;
            var value = entry.value;
            var isGroup = key.isNotEmpty;
            var title = isGroup ? key : 'dishOptionsOthers'.tr;
            var specList = isGroup ? value[0].options : value;
            return OptionSelector(
                    groupId: key, title: title, specList: specList)
                .paddingOnly(top: 20.w);
          })
        ],
      );
    });
  }

  Widget buildTitleText(String content) {
    return Text(content,
        style: TextStyle(fontSize: 26.sp, color: AppColors.text_CA7A2A));
  }
}
